const { ipcMain, BrowserWindow } = require("electron");

const getSource = (url) => {
    return new Promise((resolve, reject) => {
        const WIN = new BrowserWindow({
            width: 600,
            height: 600,
            show: false,
            webPreferences: {
                offscreen: false
            }
        });
        WIN.loadURL(url);
        WIN.webContents.on("did-finish-load", async () => {
            const title = WIN.getTitle();
            try {
                const IMAGE = await WIN.capturePage();
                if (IMAGE.isEmpty()) {
                    resolve({ msg: "无法访问该站点，请重新输入..." });
                } else {
                    const screenshot = IMAGE.toDataURL();
                    const sourceInfo = { title, screenshot, url };
                    resolve(sourceInfo);
                };
            } catch (e) {
                reject(e);
            } finally {
                WIN.close();
            };
        });
    });
};
ipcMain.handle("on-url-event", async (e, url) => {
    const sourceInfo = await getSource(url);
    return sourceInfo;
});